﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using YArchitech.Controls.HeaderGridView;

namespace YArchitech.Controls
{
	public class DataGridViewEx : DataGridViewEx
	{
		[Description("是否显示行号")]
		[DefaultValue(true)]
		public bool ShowRowHeaderNumbers
		{
			get
			{
				return this.showRowHeaderNumbers;
			}
			set
			{
				if (this.showRowHeaderNumbers != value)
				{
					base.Invalidate();
				}
				this.showRowHeaderNumbers = value;
			}
		}

		public DataGridViewEx()
		{
			this.showRowHeaderNumbers = true;
			base.RowPostPaint += this.DataGridViewEx_RowPostPaint;
		}

		protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
		{
			if (base.CurrentCell != null && base.CurrentCell.OwningColumn is DataGridViewComboBoxColumnEx)
			{
				DataGridViewComboBoxColumnEx dataGridViewComboBoxColumnEx = base.CurrentCell.OwningColumn as DataGridViewComboBoxColumnEx;
				if (dataGridViewComboBoxColumnEx.DropDownStyle != ComboBoxStyle.DropDownList)
				{
					ComboBox comboBox = e.Control as ComboBox;
					comboBox.DropDownStyle = dataGridViewComboBoxColumnEx.DropDownStyle;
					comboBox.Leave += this.combo_Leave;
				}
			}
			base.OnEditingControlShowing(e);
		}

		private void combo_Leave(object sender, EventArgs e)
		{
			ComboBox comboBox = sender as ComboBox;
			comboBox.Leave -= this.combo_Leave;
			if (base.CurrentCell != null && base.CurrentCell.OwningColumn is DataGridViewComboBoxColumnEx)
			{
				(base.CurrentCell.OwningColumn as DataGridViewComboBoxColumnEx).Items.Add(comboBox.Text);
				base.CurrentCell.Value = comboBox.Text;
			}
		}

		private void DataGridViewEx_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
		{
			if (this.showRowHeaderNumbers)
			{
				string s = (e.RowIndex + 1).ToString();
				Brush black = Brushes.Black;
				e.Graphics.DrawString(s, base.DefaultCellStyle.Font, black, (float)(e.RowBounds.Location.X + base.RowHeadersWidth / 2 - 4), (float)(e.RowBounds.Location.Y + 4));
			}
		}

		private bool showRowHeaderNumbers;
	}
}
